import * as React from 'react';
import { Props, State } from './interface';
import styles from './index.module.less';
import { GetFileUrl, UploadFile } from '@/services/index';
import { ImagePicker as AntImagePicker } from 'antd-mobile-v2';
import WxImageViewer from 'react-wx-images-viewer';
//  const Accept = ['.jpg', '.png', '.jpeg', FILES_ACCEPTS.jpeg, FILES_ACCEPTS.png];
// const MaxSize = 5; // 单张最大5m
// const MaxLength = 9; // 最多9张

export interface IFileState {
  uid: string;
  name: string;
  url?: string;
  status?: 'error' | 'success' | 'done' | 'uploading' | 'removed';
  size: number;
  type: string;
  netUid?: string;
}

export class ImagePicker extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  componentDidUpdate(prevProps) {
    if (!prevProps.receiveData.length && this.props.receiveData.length) {
      this.getFileList(this.props.receiveData);
    }
  }

  getFileList = async (list: string[]) => {
    const files = [];
    for (let i = 0; i < list.length; i++) {
      const res: any = await GetFileUrl({ id: list[i], device: 'H5' });
      // const blob = new Blob([res]);
      // const content = window.URL.createObjectURL(blob);
      files.push({
        id: list[i],
        url: res.data
      });
    }
    console.log('files', files);
    this.setState({
      files
    });
  }

  // 图片上传
  uploadImage = async (e: string | any[]) => {
    const formData = new FormData();
    const tempFile = e[e.length - 1].file;
    formData.append('file', tempFile);
    formData.append('fileType', '1');
    formData.append('device', 'H5');
    const res = await UploadFile(formData);

    console.log('res------>>>--:',res);
    return res.data;
  };

  onDelete = (index) => {
    const { onChange } = this.props;
    const newFiles = [...this.state.files];
    newFiles.splice(index, 1);
    this.setState({
      files: newFiles
    }, () => {
      onChange && onChange(this.state.files);
    });
  }

  onChange = async (files: any, type: any, index: any) => {
    const { onChange } = this.props;
    if (type == 'add') {
      const res = await this.uploadImage(files);
      this.setState((prevState) => ({
        files: prevState.files.concat(res)
      }), () => {
        onChange && onChange(this.state.files);
      });
    } else if (type === 'remove') {
      this.onDelete(index);
    }
  };

  handlePreview = async (index: number) => {
    this.setState({
      // previewImage: GetFileUrl(file.netUid),
      previewVisible: true,
      previewIndex: index
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  render() {
    const { files } = this.state;

    const { previewVisible, previewIndex } = this.state;
    const {
      props: { renderMode }
    } = this;
    return (
      <div
        className={styles.imageWrap}
        style={
          this.props.renderMode === 'detail'
            ? { padding: '0' }
            : {}
        }
      >
        <span
          className={
            styles.itemTitle +
            ' ' +
            (renderMode === 'detail' ? styles.itemTitleDetail : '')
          }
        >

          {this.props.name}
        </span>
        {
          renderMode === 'detail' && files?.length === 0 ?
            <div className={styles.defaultValue}>无</div>
            :
            (
              <AntImagePicker
                {...this.props}
                files={files}
                length="3"
                onChange={this.onChange}
                onImageClick={(index: any, fs: any) => {
                  console.log(index, fs);
                  this.handlePreview(index);
                }}
                //  selectable={files.length < 9}
                accept="image/gif,image/jpeg,image/jpg,image/png"
                disableDelete={renderMode === 'detail'}
                selectable={renderMode !== 'detail'}
              />
            )
        }
        {
          previewVisible ? <WxImageViewer onClose={this.handleCancel} urls={files.map((item) => item.url)} index={previewIndex} /> : null
        }
      </div>
    );
  }
}
